﻿

using System.Collections;
using System.Collections.Generic;
using VFramework;

namespace VFramework
{

	/// <summary>
	/// u3d事件管理部分代码
	/// 2015.04.18 - Jiangliwu
	/// </summary>
	public class EventData
	{
		public string name;
		public object data;

		public EventData (string eventName, object data)
		{
			this.name = eventName;
			this.data = data;
		}
	}


	/// <summary>
	/// 事件处理
	/// </summary>
	public class DelegateEvent
	{
		public delegate object EHandler (EventData eventData);
		public event EHandler ehandler = null;

		public bool invokeAble = true; // 是否可以调用，就是关闭了没有

		public object invoke (EventData data)
		{
			if (ehandler != null) {
				return ehandler (data);
			}
			return null;
		}
		public void removeHandler (EHandler h)
		{
			ehandler -= h;
		}

		public void addHandler (EHandler h)
		{
			ehandler += h;
		}

	}

	/// <summary>
	/// 事件管理
	/// </summary>
	public class EventMgr : ISingleton
	{
		private Dictionary<string, DelegateEvent> _eventTable = null;

		private EventMgr () { }

		public static EventMgr getInstance ()
		{
			return Singleton<EventMgr>.getInstance ();
		}

		public void init ()
		{
			_eventTable = new Dictionary<string, DelegateEvent> ();
		}

		public void release ()
		{
			clearEvent ();
		}



		public void addEvent (string eventName, DelegateEvent.EHandler h)
		{
			DelegateEvent de = null;
			if (_eventTable.ContainsKey (eventName)) {
				de = _eventTable [eventName];
			} else {
				de = new DelegateEvent ();
				_eventTable [eventName] = de;
			}

			VLogger.debug (" ---add event ---- " + eventName);
			de.addHandler (h);
		}

		/// <summary>
		/// 删除事件，若handler为null，则删除type所有handler
		/// </summary>
		/// <param name="type">eventType</param>
		/// <param name="h">handler</param>
		public void removeEvent (string type, DelegateEvent.EHandler h)
		{

			if (!_eventTable.ContainsKey (type)) {
				return;
			}

			VLogger.debug (" --- removeEvent ---- " + type);
			if (h == null) {
				_eventTable [type] = null;
				return;
			}
			_eventTable [type].removeHandler (h);
		}

		/// <summary>
		/// 清理事件
		/// </summary>
		public void clearEvent ()
		{
			VLogger.debug (" ------------------ clear events -------------- ");
			_eventTable.Clear ();
		}

		/// <summary>
		/// 分发事件,注意:返回值为最后绑定的handler返回值,
		/// </summary>
		/// <returns>The event.</returns>
		/// <param name="type">事件名称</param>
		/// <param name="data">字典键值对</param>
		public object dispatchEvent (string type, object data = null)
		{
			if (!_eventTable.ContainsKey (type)) {
				VLogger.error (" ---- cannot find handler = " + type);
				return null;
			}
			if (_eventTable [type].invokeAble) {
				return _eventTable [type].invoke (new EventData (type, data));
			} else {
				VLogger.info ("event=" + type + ", invokeable = false!!");
				return null;
			}
		}
	}
}